package com.dacool.fragment;

import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.hardware.Camera.Area;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.dacool.app.sale.R;
import com.dacool.config.Config;
import com.dacool.dialog.BasePickerDialog.PickerDialogDelegate;
import com.dacool.dialog.PickCityDialog;
import com.dacool.http.AddAddressRequest;
import com.dacool.http.BaseRequest;
import com.dacool.http.BaseRequest.ResponseHandler;
import com.dacool.http.GetShipRegionListRequest;
import com.dacool.http.UpdateAddressRequest;
import com.dacool.model.DCAddress;
import com.dacool.model.DCUser;
import com.dacool.model.Region;
import com.dacool.model.ShipRegion;
import com.dacool.util.ViewUtils;

public class AddressInfoFragment extends BaseFragment {

	private DCAddress address;
	private int shipRegionId;
	// private Region selectedRegion = Config.sharedConfig()
	// .getRegionsByParentID(0).get(0);
	// private boolean extrafee;

	private EditText deliveryManInput;
	private EditText regionInput;
	private EditText addressInput;
	private EditText mobileInput;
	private LinearLayout deliveryFeeRegion;
	private EditText remarkInput;
	private Button saveButton;

	private Region region;

	private ShipRegion selectedShipRegion;
	private int selectedShipRegionId;

	public boolean selectMode = false;

	private ArrayList<ShipRegion> regions = new ArrayList<ShipRegion>();;
	private ArrayList<ViewHolder> regionOptions = new ArrayList<AddressInfoFragment.ViewHolder>();;

	// private LinearLayout feeOption1;
	// private LinearLayout feeOption2;

	public void setAddress(DCAddress addr) {
		this.address = addr;
		if (address != null) {
			// Log.d("test", "set address" + address.address);
			selectedShipRegion = address.shipRegion;
			selectedShipRegionId = address.shipRegionId;
			ArrayList<Region> regions = Config.sharedConfig()
					.getRegionsByParentID(0);
			for (Region r : regions) {
				if (r.name.equals(address.area)) {
					region = r;
				}
			}
			// extrafee = address.extraTransFeeNeeded;
		}

	}

	@Override
	public void onViewCreated(View view, Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onViewCreated(view, savedInstanceState);
		deliveryManInput = ViewUtils.findViewById(view, R.id.nameInput);
		if (address != null)
			deliveryManInput.setText(address.deliveryMan);
		regionInput = ViewUtils.findViewById(view, R.id.regionInput);
		// Log.d("test", "address" + address);
		if (address != null)
			regionInput.setText(address.area);
		if (region == null) {
			regionInput.setHint("请选择");
			regionInput.setText("");
		}
		addressInput = ViewUtils.findViewById(view, R.id.addressInput);
		if (address != null)
			addressInput.setText(address.address);
		mobileInput = ViewUtils.findViewById(view, R.id.phoneInput);
		if (address != null)
			mobileInput.setText(address.mobileNo);
		deliveryFeeRegion = ViewUtils
				.findViewById(view, R.id.deliverFeeChooser);
		remarkInput = ViewUtils.findViewById(view, R.id.memoInput);
		regionInput.setOnClickListener(this);
		saveButton = ViewUtils.findViewById(view, R.id.saveButton);

		// feeOption1 = ViewUtils.findViewById(view, R.id.fee1);
		// feeOption1.setOnClickListener(this);
		// ((TextView) feeOption1.findViewById(R.id.detalText))
		// .setText("北京市五环内免费");

		// feeOption2 = ViewUtils.findViewById(view, R.id.fee2);
		//
		// ((TextView) feeOption2.findViewById(R.id.detalText))
		// .setText("远郊县区每次送货加收10元");
		// feeOption2.setOnClickListener(this);
		saveButton.setOnClickListener(this);
		// if (!extrafee) {
		// ((ImageView) feeOption1.findViewById(R.id.checkBox))
		// .setImageResource(R.drawable.icon_check_green);
		// ((ImageView) feeOption2.findViewById(R.id.checkBox))
		// .setImageDrawable(null);
		// } else {
		// ((ImageView) feeOption2.findViewById(R.id.checkBox))
		// .setImageResource(R.drawable.icon_check_green);
		// ((ImageView) feeOption1.findViewById(R.id.checkBox))
		// .setImageDrawable(null);
		// }
		if (address != null) {
			loadShipRegions(address.area);
		}
	}

	private void loadShipRegions(String area) {
		new GetShipRegionListRequest().setArea(area)
				.setHandler(new ResponseHandler() {

					@Override
					public void handleResponse(BaseRequest request,
							int statusCode, String errorMsg, String response) {
						if (statusCode != 200) {
							ViewUtils.showToast("通讯失败", Toast.LENGTH_LONG);
						} else {
							boolean success = false;
							ArrayList<ShipRegion> sRegions = null;
							try {
								JSONObject json = new JSONObject(response);
								success = json.optBoolean("success", false);
								JSONArray array = json.getJSONArray("data");
								sRegions = new ArrayList<ShipRegion>();
								for (int i = 0; i < array.length(); i++) {
									JSONObject obj = array.getJSONObject(i);
									ShipRegion sregion = new ShipRegion();
									sregion.id = obj.getInt("id");
									sregion.name = obj.getString("value");
									sRegions.add(sregion);
								}
							} catch (JSONException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
							if (success) {
								regions = sRegions;
								regionOptions.clear();
								ViewUtils.runInMainThread(new Runnable() {

									@Override
									public void run() {
										// TODO Auto-generated method stub
										deliveryFeeRegion.removeAllViews();
										for (int i = 0; i < regions.size(); i++) {
											ViewHolder holder = ViewHolder
													.createViewHolder(LayoutInflater
															.from(getActivity()));
											ShipRegion sregion = regions.get(i);
											if ((selectedShipRegion != null && selectedShipRegion.id == sregion.id)
													|| selectedShipRegionId == sregion.id) {
												holder.checkBox
														.setImageResource(R.drawable.icon_check_green);
											} else {
												holder.checkBox
														.setImageDrawable(null);
											}
											holder.label.setText(sregion.name);
											holder.container.setTag(i);
											holder.container
													.setOnClickListener(AddressInfoFragment.this);
											deliveryFeeRegion
													.addView(holder.container);
											regionOptions.add(holder);
										}
									}
								});
							}

						}
					}
				}).start();
	}

	private static class ViewHolder {
		public static ViewHolder createViewHolder(LayoutInflater inflater) {
			ViewHolder holder = new ViewHolder();
			View view = inflater.inflate(R.layout.deliveryfeeitem, null);
			holder.container = view;
			holder.checkBox = ViewUtils.findViewById(view, R.id.checkBox);
			holder.label = ViewUtils.findViewById(view, R.id.detalText);
			return holder;
		}

		public View container;
		public ImageView checkBox;
		public TextView label;
	}

	@Override
	protected int myLayoutID() {
		// TODO Auto-generated method stub
		return R.layout.frag_addressinfo;
	}

	@Override
	protected View myView() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public String titleText() {
		// TODO Auto-generated method stub
		return address == null ? "新增地址" : "收货地址";
	}

	@Override
	protected boolean showDefaultSecondLeftButton() {
		// TODO Auto-generated method stub
		return true;
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		if (regionInput == v) {
			new PickCityDialog(getActivity())
					.setRegions(Config.sharedConfig().getRegionsByParentID(0))
					.setDelegate(new PickerDialogDelegate() {

						@Override
						public void selectedItemAtIndex(int index) {
							// TODO Auto-generated method stub
							region = Config.sharedConfig()
									.getRegionsByParentID(0).get(index);
							regionInput.setText(region.name);
							loadShipRegions(region.name);
						}

						@Override
						public void didCancel() {
							// TODO Auto-generated method stub

						}
					}).show();
		} else if (v.getTag() instanceof Integer) {
			for (ViewHolder holder : regionOptions) {
				if (holder.container == v) {
					holder.checkBox
							.setImageResource(R.drawable.icon_check_green);
					selectedShipRegion = regions.get(regionOptions
							.indexOf(holder));
					selectedShipRegionId = selectedShipRegion.id;
				} else {
					holder.checkBox.setImageDrawable(null);
				}
			}
			// extrafee = feeOption1 != v;
			// if (!extrafee) {
			// ((ImageView) feeOption1.findViewById(R.id.checkBox))
			// .setImageResource(R.drawable.icon_check_green);
			// ((ImageView) feeOption2.findViewById(R.id.checkBox))
			// .setImageDrawable(null);
			// } else {
			// ((ImageView) feeOption2.findViewById(R.id.checkBox))
			// .setImageResource(R.drawable.icon_check_green);
			// ((ImageView) feeOption1.findViewById(R.id.checkBox))
			// .setImageDrawable(null);
			// }

		} else if (saveButton == v) {
			if (!verify())
				return;
			this.showProgressDialog(null, false);
			if (this.address == null) {
				new AddAddressRequest()
						.setAddress(addressInput.getText().toString())
						.setDeliveryMan(deliveryManInput.getText().toString())
						.setMemberId(DCUser.sharedUser().getUserId())
						.setMobile(mobileInput.getText().toString())
						.setArea(regionInput.getText().toString())
						.setRemark(remarkInput.getText().toString())
						.setShipRegionId(selectedShipRegionId)
						.setHandler(new ResponseHandler() {

							@Override
							public void handleResponse(BaseRequest request,
									int statusCode, String errorMsg,
									String response) {
								// TODO Auto-generated method stub
								AddressInfoFragment.this
										.dismissProgressDialog();
								boolean success = false;
								String errmsg = null;
								if (statusCode != 200) {
									success = false;
								} else {
									try {
										JSONObject object = new JSONObject(
												response);
										success = object.optBoolean("success",
												false);
										errmsg = object.optString("msg", null);
										if (success) {
											DCAddress address = new DCAddress();
											address.address = addressInput
													.getText().toString();
											address.deliveryMan = deliveryManInput
													.getText().toString();
											address.area = regionInput
													.getText().toString();
											// address.districtID =
											// selectedRegion.id;
											address.shipRegion = selectedShipRegion;
											address.mobileNo = mobileInput
													.getText().toString();
											address.remark = remarkInput
													.getText().toString();
											DCUser.sharedUser().address = address;
											DCUser.sharedUser().save();
											if (selectMode)
												getContainerActivity().pop(2);
											else
												getContainerActivity()
														.handleBackButton();
										}
									} catch (JSONException e) {
										// TODO Auto-generated catch block
										e.printStackTrace();
									}
								}

								if (!success) {
									String msg = errmsg != null ? errmsg
											: "保存地址失败";
									ViewUtils.showToast(msg, Toast.LENGTH_LONG);
								}

							}
						}).start();
			} else {
				new UpdateAddressRequest()
						.setAddress(addressInput.getText().toString())
						.setDeliveryMan(deliveryManInput.getText().toString())
						.setId(address.id)
						.setMobile(mobileInput.getText().toString())
						.setRegion(regionInput.getText().toString())
						.setRemark(remarkInput.getText().toString())
						.setShipRegionId(selectedShipRegionId)
						.setHandler(new ResponseHandler() {

							@Override
							public void handleResponse(BaseRequest request,
									int statusCode, String errorMsg,
									String response) {
								// TODO Auto-generated method stub
								AddressInfoFragment.this
										.dismissProgressDialog();
								boolean success = false;
								String errmsg = null;
								if (statusCode != 200) {
									success = false;
								} else {
									try {
										JSONObject object = new JSONObject(
												response);
										success = object.optBoolean("success",
												false);
										errmsg = object.optString("msg", null);
										if (success) {
											address.address = addressInput
													.getText().toString();
											address.deliveryMan = deliveryManInput
													.getText().toString();
											// address.districtID =
											// selectedRegion.id;
											address.area = regionInput
													.getText().toString();
											address.shipRegion = selectedShipRegion;
											address.mobileNo = mobileInput
													.getText().toString();
											address.remark = remarkInput
													.getText().toString();
											DCUser.sharedUser().address = address;
											DCUser.sharedUser().save();
											if (selectMode)
												getContainerActivity().pop(2);
											else
												getContainerActivity()
														.handleBackButton();
										}
									} catch (JSONException e) {
										// TODO Auto-generated catch block
										e.printStackTrace();
									}
								}

								if (!success) {
									String msg = errmsg != null ? errmsg
											: "保存地址失败";
									ViewUtils.showToast(msg, Toast.LENGTH_LONG);
								}

							}
						}).start();
			}
		}

		super.onClick(v);
	}

	private boolean verify() {
		if (deliveryManInput.getText().length() == 0) {
			Toast.makeText(getActivity(), "请输入收货人", Toast.LENGTH_LONG).show();
			return false;
		}

		if (addressInput.getText().length() == 0) {
			Toast.makeText(getActivity(), "请输入收货地址", Toast.LENGTH_LONG).show();
			return false;
		}

		if (region == null) {
			Toast.makeText(getActivity(), "请选择所在地区", Toast.LENGTH_LONG).show();
			return false;
		}

		Pattern p = Pattern.compile("^1\\d{10}$");
		Matcher matcher = p.matcher(mobileInput.getText().toString());

		if (!matcher.matches()) {
			Toast.makeText(getActivity(), "请输入11位手机号", Toast.LENGTH_LONG)
					.show();
			return false;
		}
		return true;
	}
}
